package com.aegis.common.web.aspect;

import com.aegis.common.core.annotation.Trimmed;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.lang.reflect.Field;

/**
 * @Author wuweixin
 *
 * @Version 1.0
 * @Descritube
 */
@Aspect
public class TrimmedFieldAspect {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.GetMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PutMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.DeleteMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PatchMapping)")
    public void trimStringFields(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            if (arg == null) continue;
            trimAnnotatedFields(arg);
        }
    }

    private void trimAnnotatedFields(Object target) {
        Class<?> clazz = target.getClass();
        while (clazz != null && clazz != Object.class) {
            for (Field field : clazz.getDeclaredFields()) {
                if (field.getType() == String.class && field.isAnnotationPresent(Trimmed.class)) {
                    field.setAccessible(true);
                    try {
                        String value = (String) field.get(target);
                        if (value != null) {
                            field.set(target, value.trim());
                        }
                    } catch (IllegalAccessException e) {
                        // log if needed
                    }
                }
            }
            clazz = clazz.getSuperclass(); // 支持父类字段
        }
    }

}
